package com.icebartech.base.modules.user.service.impl;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.RandomStringUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.icebartech.base.modules.user.dto.AdminUserCoreDTO;
import com.icebartech.base.modules.user.mapper.AdminUserCoreMapper;
import com.icebartech.base.modules.user.model.AdminUserCore;
import com.icebartech.base.modules.user.model.AdminUserLoginInfo;
import com.icebartech.base.modules.user.model.AppRole;
import com.icebartech.base.modules.user.service.AdminUserCoreService;
import com.icebartech.base.modules.user.service.AdminUserLoginInfoService;
import com.icebartech.base.modules.user.service.AppRoleService;
import com.icebartech.core.components.AliyunOSSComponent;
import com.icebartech.core.conf.AliyunProperties;
import com.icebartech.core.constants.IcebartechConstants;
import com.icebartech.core.modules.AbstractService;
import com.icebartech.core.modules.BaseMapper;
import com.icebartech.core.utils.CommonUtil;
import com.icebartech.core.utils.ExtBeanUtils;

@Service
public class AdminUserCoreServiceImpl extends AbstractService implements AdminUserCoreService {

	@Autowired
	private AdminUserCoreMapper adminUserCoreMapper;
	
	@Autowired
	private AdminUserLoginInfoService adminUserLoginInfoService;
	
	@Autowired
	private AppRoleService appRoleService;
	
	@Autowired
	private AliyunProperties aliyunProperties;
	
	@Autowired
	private AliyunOSSComponent aliyunOSSComponent;
	
	@Override
	public BaseMapper getBaseMapper() {
		return this.adminUserCoreMapper;
	}

	/**
	 * 注册一个普通教师用户账号
	 * @param userCore 账号基本信息
	 * @param userLoginInfo 登录信息，包含账号和密码
	 * @return
	 */
	public AdminUserCore registerAdminUserCore(AdminUserCore userCore, AdminUserLoginInfo userLoginInfo){
		
		String slat = RandomStringUtils.randomAlphanumeric(8);
		userLoginInfo.setPwd2(slat);
		userLoginInfo.setPwd(CommonUtil.pwdMd5(userLoginInfo.getPwd().trim(), slat));
		userLoginInfo.setLoginCount(1);
		int userCount = this.add(userCore);
		
		if(userCount > 0){
			userLoginInfo.setUserId(userCore.getUserId());
		}
		int rowCount = adminUserLoginInfoService.add(userLoginInfo);
		if(rowCount > 0 && userCount > 0){
			return userCore;
		}
		return null;
	}
	
	
	/**
	 * 检查用户名是否存在
	 * @param userName 用户名
	 * @return
	 */
	public boolean checkUserName(String userName){
		return findAdminUserCoreByUserName(userName) != null;
	}
	
	/**
	 * 根据用户名返回唯一的用户记录
	 * @param userName 用户名
	 * @return
	 */
	public AdminUserCore findAdminUserCoreByUserName(String userName){
		return adminUserCoreMapper.selectByUserName(userName);
	}

	/**
	 * 分页查找系统管理账户信息
	 * @param pageIndex 当前页
	 * @param pageSize 分页大小
	 * @param paramMap 查询条件
	 * @return
	 */
	@Override
	public PageInfo<Map<String, Object>> findUserCoreAndRoleByPage(int pageIndex, int pageSize,
			Map<String, Object> paramMap) {
		PageHelper.startPage(pageIndex, pageSize);
		List<Map<String, Object>> adminUserCoreList = adminUserCoreMapper.findAdminUserCoreMapPageHolder(paramMap);
		PageInfo<Map<String, Object>> pageInfo = new PageInfo<>(adminUserCoreList);
		return pageInfo;
	}
	
	@Override
	public PageInfo<AdminUserCoreDTO> findAdminUserCoreByPage(Map<String, Object> paramMap, int pageIndex, int pageSize) {
		PageHelper.startPage(pageIndex, pageSize);
		List<AdminUserCore> list = adminUserCoreMapper.findAdminUserCoreByPage(paramMap);
		PageInfo<AdminUserCore> pageInfo = new PageInfo<>(list);
		PageInfo<AdminUserCoreDTO> extPageInfo = new PageInfo<>();
		extPageInfo.setTotal(pageInfo.getTotal());
		extPageInfo.setPages(pageInfo.getPages());
		List<AdminUserCoreDTO> extList = new ArrayList<>();
		if(CollectionUtils.isNotEmpty(pageInfo.getList())){
			for(AdminUserCore userCore : pageInfo.getList()){
				AdminUserCoreDTO coreExt = assembleUserCoreExt(userCore);
				extList.add(coreExt);
			}
		}
		extPageInfo.setList(extList);
		return extPageInfo;
	}
	
	@Override
	public AdminUserCoreDTO findUserCoreExtByUserId(Long userId) {
		AdminUserCore userCore = findById(userId);
		return assembleUserCoreExt(userCore);
	}
	
	@Override
	public AdminUserCoreDTO assembleUserCoreExt(AdminUserCore userCore){
		AdminUserCoreDTO coreExt = new AdminUserCoreDTO();
		try{
			ExtBeanUtils.copyProperties(coreExt, userCore);
			String roleName = "--";
			if(userCore.getAppRoleId() != null){
				//设置角色名称
				AppRole appRole = appRoleService.findById(Long.valueOf(userCore.getAppRoleId()));
				if(appRole != null){
					roleName = appRole.getRoleName();
				}
			}
			coreExt.setRoleName(roleName);
			//设置登录时间
			AdminUserLoginInfo loginInfo = adminUserLoginInfoService.findById(userCore.getUserId());
			if (null != loginInfo){
				coreExt.setLastLoginTime(loginInfo.getLastLoginTime());
			}
			
		}catch(Exception e){
			return null;
		}
		return coreExt;
	}
	
	@Override
	public String getUserAvatarUrl(Long userId) {
        String avatar = aliyunProperties.getOssEndpoint() + "master-head.png";
        AdminUserCore userCore = findById(userId);
        if (userCore == null) {
            return null;
        }
        String fileId = userCore.getAvatar();
        String suffix = userCore.getSuffix();
        if (StringUtils.isNotBlank(fileId) && StringUtils.isNotBlank(suffix)) {
            avatar = aliyunOSSComponent.getFileUrl(fileId + "." + suffix);
        }
        return avatar;
    }
	
	@Override
	public boolean deleteAdminUser(Long userId) {
		adminUserLoginInfoService.deleteById(userId);
		this.deleteById(userId);
		return true;
	}
}
